require 'rype'

module Fabriq
  module Adapter

    class RypeAdapter

      def attach(&block)
        ::Rype.attach
      end

      def wait
        ::Rype.thread.join
      end

      def message_received(&block)
        Rype.on(:chatmessage_received) do |chatmessage|
          chatmessage.chat do |chat|
            chatmessage.body do |body|
              chatmessage.from_name do |from_name|
                Thread.new { yield({ from_name: from_name, body: body, room_id: chat.chatname }) }
              end
            end
          end
        end
      end

      def send_message(chat, body)
        chat.send_message(body)
      end

      def available_rooms(&block)
        Rype::Chat.all do |chats|
          yield chats
        end
      end

      def load_room_information(room, &block)
        room.topic do |topic|
          room.members do |members|
            yield({ topic: topic, id: room.chatname, members: members, raw: room })
          end
        end
      end

    end

  end
end